# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 16:21:12 2018

@author: Luther
"""

import requests
import pandas as pd


def getRoute(lat1, lng1, lat2, lng2):
    url = "http://api.map.baidu.com/direction/v2/driving?origin={0:},{1:}&destination={2:},{3:}&ak=5mSNiWKjGK0FZtuL5yc09GRb4wHYDiNU".format(
        lat1, lng1, lat2, lng2)
    results = []
    try:
        r = requests.get(url, timeout=120)
        r.raise_for_status
        d = r.json()["result"]["routes"][0]
        dist = d["distance"] / 1000
        time = d["duration"] / 3600
        results.append(dist)
        results.append(time)
    except:
        results.append(0)
        results.append(0)
    return results


df = pd.read_excel("route.xlsx")
dl = []
tl = []
for i in range(len(df)):
    lat1 = df.lat[i]
    lng1 = df.lng[i]
    lat2 = df.station_lat[i]
    lng2 = df.station_lng[i]
    l = getRoute(lat1, lng1, lat2, lng2)
    dl.append(l[0])
    tl.append(l[1])
    print("\r当前进度: {:.2f}%".format((i + 1) * 100 / len(df)), end="")

df["routedist"] = dl
df["timespan"] = tl

df.to_excel("route.xlsx")
